<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------
namespace app\common\command\crontab;

use easemob\EasemobIm;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;

class Chat
{
    /**
     * User: Simony
     * Function: 任何一个定时任务文件
     */
    public static function execute($functionName)
    {
        self::$functionName();
    }

    /**
     * User: Simony
     * Function:导出聊天记录
     * @param null $time 时间搓
     * @return array
     */
    public static function exportChatRecord($time = null)
    {

        $download_time = is_null($time) ? date('YmdH', time() - 3600 * 1) : date('YmdH', $time);
        //时间校验
        $chatRecordModel = model('common/chat/ChatRecord');
        $create_time = $chatRecordModel->getMax([], 'create_time');
        if (date('YmdH', $create_time) >= $download_time) return ds_arr(ERROR, '请勿重复拉取数据1');

        $easemobIm = new EasemobIm();
        $record_res = $easemobIm->getChatRecord($download_time);


        if ($record_res['code'] == ERROR) return ds_arr($record_res['code'], $record_res['msg'], $record_res['result']);
        $record = $record_res['result'];

        try {
            //下载
            $client = new Client();
            $saveFilePath = ROOT_PATH . DS . 'record_log.gz';
            $response = $client->get($record['data'][0]['url'], ['save_to' => $saveFilePath]);

            //解压文件 删除
            self::decompression($saveFilePath);

            //读取 删除
            $record_log_str = file_get_contents(ROOT_PATH . DS . 'record_log');
            $record_log = explode("\n", trim($record_log_str));
            $record_log_str = '[' . implode(',', $record_log) . ']';
            $record_log_data = json_decode($record_log_str, true);
            @unlink(ROOT_PATH . DS . 'record_log');
            if (empty($record_log_data)) return ds_arr(ERROR, '暂无数据2');

            $data = [];
            foreach ($record_log_data as $v) $data[$v['msg_id']] = $v;

            $where['msg_id'] = array_keys($data);
            $exit_data = $chatRecordModel->getCol('msg_id', $where);
            $array_diff = array_values(array_diff($where['msg_id'], $exit_data)); //排除已存在的数据
            if (empty($array_diff)) return ds_arr(ERROR, '请勿重复拉取数据2');

            $current_time = time();
            $all_add_data = [];
            foreach ($array_diff as $v) {
                $temp = $data[$v];
                $add_data = [
                    'member_id' => $temp['from'], //发消息用户id
                    'msg_id' => $temp['msg_id'], //环信消息id
                    'receive_flag_id' => $temp['to'], //标识id 接收会员id或者，接收的组id
                    //拓展字段
                    'receive_type' => isset($temp['payload']['ext']['receive_type']) ? $temp['payload']['ext']['receive_type'] : 1, //接收类型 0全体会员 1会员 2组
                    'msg_type' => isset($temp['payload']['ext']['msg_type']) ? $temp['payload']['ext']['msg_type'] : 0, //0聊天消息,1评价通知 2节目通知 3报名通知 4申请通知 5评论通知 6收益提醒通知 7消息通知
                    'is_read' => isset($temp['payload']['ext']['is_read']) ? $temp['payload']['ext']['is_read'] : 1, //是否已读 0未读 1已读
                    'type' => isset($temp['payload']['ext']['receive_type']) ? $temp['payload']['ext']['receive_type'] : 0, //-1提示,0文字,1图片,2语音,3视频,4文件,5红包,6位置
                    //内容
                    'content' => isset($temp['payload']['bodies'][0]['msg']) ? $temp['payload']['bodies'][0]['msg'] : '', //内容
                    'url' => isset($temp['payload']['bodies'][0]['url']) ? $temp['payload']['bodies'][0]['url'] : '', //链接
                    'data' => json_encode($temp),
                    'time' => sprintf('%.0f', $temp['timestamp'] / 1000),
                    'create_time' => $current_time,
                ];

                $all_add_data[] = $add_data;

            }


            $res = $chatRecordModel->addAll($all_add_data);
            return $res ? ds_arr(SUCCESS, '拉取数据成功', $array_diff) : ds_arr(SUCCESS, '拉取数据失败');
        } catch (\Exception $e) {
            return ds_arr(SUCCESS, '失败：' . $e->getMessage());
        }

    }


    /**
     * User: Simony
     * Function:解压文件 删除
     * @param $save_url
     */
    public static function decompression($save_url)
    {
        $buffer_size = 4096;
        $out_file_name = str_replace('.gz', '', $save_url);
        $file = gzopen($save_url, 'rb');
        $out_file = fopen($out_file_name, 'wb');
        while (!gzeof($file)) {
            fwrite($out_file, gzread($file, $buffer_size));
        }
        @unlink($save_url);
        fclose($out_file);
        gzclose($file);
    }
}


